package sb.de.advanceShopper.dataBase;

import java.util.ArrayList;
import java.util.List;

import sb.de.advanceShopper.model.City;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CitiesDataSource {

	private SQLiteDatabase database;

	private ShopsSQLiteHelper dbHelper;

	private String[] allColumns = { CitiesSQLiteHelper.CITIES_TCID,
			CitiesSQLiteHelper.CITIES_TCNAME, CitiesSQLiteHelper.CITIES_TCCOUNTRY};

	public CitiesDataSource(Context context) {
		dbHelper = new ShopsSQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public City createCity(String name, int country) {
		open();
		
		City res;
		ContentValues values = new ContentValues();
		values.put(CitiesSQLiteHelper.CITIES_TCNAME, name);
		values.put(CitiesSQLiteHelper.CITIES_TCCOUNTRY, country);
		long insertId = database.insert(CitiesSQLiteHelper.CITIES_TABLE, null,
				values);

		 Cursor cursor = database.query(CitiesSQLiteHelper.CITIES_TABLE,
		 allColumns, CitiesSQLiteHelper.CITIES_TCID + " = " + insertId, null,
		 null, null, null);
		 cursor.moveToFirst();
		 
		 res = cursorToCity(cursor);
		 cursor.close();
		 close();
		 
		 return res;
	}

	public void deleteCity(City city) {
		open();
		
		long id = city.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(CitiesSQLiteHelper.CITIES_TABLE, CitiesSQLiteHelper.CITIES_TCID
				+ " = " + id, null);
		
		close();
	}

	public List<City> getAllCities() {
		open();
		
		List<City> cities = new ArrayList<City>();
		Cursor cursor = database.query(CitiesSQLiteHelper.CITIES_TABLE, allColumns,
				null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			City city = cursorToCity(cursor);
			cities.add(city);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		
		return cities;
	}

	private City cursorToCity(Cursor cursor) {
		return new City(cursor.getInt(0), cursor.getString(1),
				cursor.getInt(2));
	}

	public City getCityByName(String cityName, int countryID) {
		List<City> tmpCities = getAllCities();
		for (City city : tmpCities) {
			if(cityName.equals(city.getName()) && countryID == city.getCountry()) {
				return city;
			}
		}
		return null;
	}
}
